<template>
  <div class="lxgzdscannew">
    <van-overlay :show="overlayShow" :z-index="1000">
      <div style="display: flex;align-items: center;justify-content: center;height: 100%;">
        <van-loading type="spinner" color="#1989fa">请稍候...</van-loading>
      </div>
    </van-overlay>
    <div style="margin-bottom: 3vh;">
      <van-collapse v-model="activeNames" class="cellvalue">
        <van-collapse-item title="基本信息" name="1">
          <van-cell-group>
            <input type="hidden" :value="jsonData.userid" />
            <van-field label="单据日期" :value="jsonData.billdate" readonly />
            <van-field label="负责人" :value="jsonData.username" readonly />
            <van-field readonly clickable name="picker" :value="value" label="单据类型" @click="showPicker = true" />
            <van-popup v-model="showPicker" position="bottom">
              <van-picker show-toolbar :columns="columns" @confirm="onConfirm" @cancel="showPicker = false" />
            </van-popup>
            <input type="hidden" v-model="tradeList.valuehidden" />
            <van-field clearable required v-model="tradeList.value" label="库存减少方" right-icon="search" @input="clearRefValue(tradeList)" @clear="clearRefValue(tradeList)" @change="openRef(0)" @click-right-icon="openRef(0)" :error-message="errormsg1" />
            <input type="hidden" v-model="tagendList.valuehidden" />
            <van-field clearable required v-model="tagendList.value" label="库存增加方" right-icon="search" @input="clearRefValue(tagendList)" @clear="clearRefValue(tagendList)" @change="openRef(1)" @click-right-icon="openRef(1)" :error-message="errormsg2" />
          </van-cell-group>
        </van-collapse-item>
      </van-collapse>
    </div>

    <van-swipe-cell v-for="(item, index) in scanList" :key="item.code">
      <van-cell :border="true">
        <template #title>
          <span>{{ item.code }}</span><br>
          <span style="font-size: 12px;color: #969799;" v-html="item.label"></span>
        </template>
      </van-cell>
      <template slot="right">
        <van-button class="swipe-button" square type="danger" text="删除" @click="scanList.splice(index, 1)" />
      </template>
    </van-swipe-cell>
    <div style="margin:1vh 2vh 10vh">
      <van-button round block type="info" native-type="submit" @click="show = true" icon="scan">扫一扫</van-button>
    </div>
    <van-action-sheet v-model="show" :actions="actions" cancel-text="取消" close-on-click-action @select="onSelect" />
    <van-tabbar v-model="active" safe-area-inset-bottom>
      <template>
        <van-tabbar-item @click="save">保存</van-tabbar-item>
      </template>
    </van-tabbar>
  </div>
</template>

<script>
import Vue from 'vue'
import {
  Search, List, Cell, PullRefresh, Toast, Tabbar, TabbarItem, Popup, DatetimePicker, ActionSheet, Tab, Tabs, Collapse, CollapseItem, CheckboxGroup, Checkbox, Uploader, Overlay, Loading
} from 'vant'
import qs from 'qs'
import wx from 'weixin-js-sdk'
import dd from 'dingtalk-jsapi'
Vue.use(Search).use(List).use(Cell).use(PullRefresh).use(Toast).use(Tabbar).use(TabbarItem).use(Popup).use(DatetimePicker).use(ActionSheet).use(Tab).use(Tabs).use(Collapse).use(CollapseItem).use(CheckboxGroup).use(Checkbox).use(Uploader).use(Overlay).use(Loading)
export default {
  name: 'lxgzdscannew',
  data () {
    return {
      overlayShow: false,
      active: 0,
      scanList: [],
      activeNames: ['1'],
      jsonData: {},
      tagendList: {},
      tradeList: {},
      clickmodel: {},
      clickindex: -1,
      show: false,
      errormsg1: '',
      errormsg2: '',
      actions: [{ name: '微信扫码(推荐)' }, { name: '钉钉扫码' }],
      showPicker: false,
      columns: ['发货', '退货'],
      value: '发货'
    }
  },
  mounted: function () {
    this.axios({
      method: 'post',
      url: '/api/lxgzds.scannew.do'
    }).then(res => {
      this.jsonData = res.data.jsondata
    }).catch(res => {
      this.reserror(res)
    })
  },
  methods: {
    onSelect (item) {
      if (item.name === '微信扫码(推荐)') {
        var u = navigator.userAgent
        let url = sessionStorage.getItem('wxurl')
        var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
        var isQiye = /(wxwork)/i.test(u)
        if (!isIOS || isQiye) {
          url = location.href.split('#')[0]
        }
        let that = this
        this.axios({
          method: 'post',
          url: '/api/wechatscan.do',
          data: qs.stringify({
            url: encodeURIComponent(url)
          })
        }).then((res) => {
          if (res.data.flag === '1') {
            Toast(res.data.des)
            if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
              this.loginout()
            }
          } else {
            let a = res.data
            //console.log(a)
            wx.config({
              debug: false,
              appId: a.appId,
              timestamp: a.timestamp,
              nonceStr: a.nonceStr,
              signature: a.signature,
              jsApiList: ['scanQRCode']
            })
            wx.error(function (res) {
              //console.log('微信js-sdk配置失败')
              Toast('微信配置异常，请联系系统管理员' + res.errMsg)
            })
            wx.ready(function () {
              wx.scanQRCode({
                needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
                success: function (res) {
                  var result = res.resultStr // 当needResult 为 1 时，扫码返回的结果
                  if (result.substr(0, 4) === 'CODE') {
                    result = result.split(',')[1]
                  }
                  var scanflag = true
                  var scode = result.substring(12, 15)
                  var flag = true
                  var cs = result.substring(3, 12) // 厂商
                  var ph = result.slice(26, -6)// 批号
                  that.scanList.forEach((item) => {
                    if (item.code === result) {
                      scanflag = false
                    }
                  })
                  if (scanflag) {
                    that.jsonData.productList.forEach((item) => {
                      if (item.scode === scode) {
                        if (cs === '697174170') {
                          cs = '科睿驰（深圳）医疗科技发展有限公司'
                        } else if (cs === '697141165') {
                          cs = '科睿驰（北京）医疗科技发展有限公司'
                        }
                        var label = '厂商:' + cs + '<br>' + '产品编码:' + item.scode + '<br>' + '产品名称:' + item.sname + '<br>' + '规格:' + item.sspec + '<br>' + '批号:' + ph + '<br>' + '序列号:' + result
                        flag = false
                        that.scanList.unshift({
                          code: result,
                          label: label
                        })
                      }
                    })
                    if (flag) {
                      Toast('产品不存在，请重新扫码')
                    }
                  } else {
                    Toast('条形码已存在')
                  }
                },
                fail: function (res) {
                  Toast('失败' + res.errMsg)
                }
              })
            })
          }
        }).catch((res) => {
          this.reserror(res)
        })
      } else if (item.name === '钉钉扫码') {
        let that = this
        dd.ready(function () {
          dd.biz.util.scan({
            type: 'all',
            onSuccess: function (data) {
              var result = data.text
              var flag = true
              var scanflag = true
              var scode = result.substring(12, 15)
              var cs = result.substring(3, 12) // 厂商
              var ph = result.slice(26, -6)// 批号
              that.scanList.forEach((item) => {
                if (item.code === result) {
                  scanflag = false
                }
              })
              if (scanflag) {
                that.jsonData.productList.forEach((item) => {
                  if (item.scode === scode) {
                    if (cs === '697174170') {
                      cs = '科睿驰（深圳）医疗科技发展有限公司'
                    } else if (cs === '697141165') {
                      cs = '科睿驰（北京）医疗科技发展有限公司'
                    }
                    var label = '厂商:' + cs + '<br>' + '产品编码:' + item.scode + '<br>' + '产品名称:' + item.sname + '<br>' + '规格:' + item.sspec + '<br>' + '批号:' + ph + '<br>' + '序列号:' + result
                    flag = false
                    that.scanList.unshift({
                      code: result,
                      label: label
                    })
                  }
                })
                if (flag) {
                  Toast('产品不存在，请重新扫码')
                  var label = '厂商:' + cs + '<br>' + '产品编码:' + item.scode + '<br>' + '产品名称:' + item.sname + '<br>' + '规格:' + item.sspec + '<br>' + '批号:' + ph + '<br>' + '序列号:'
                  flag = false
                  that.scanList.unshift({
                    code: result,
                    label: label
                  })
                }
              } else {
                Toast('条形码已存在')
              }
            },
            onFail: function (err) {
              Toast(JSON.stringify(err))
            }
          })
        })
      }
    },
    save () {
      if (this.tradeList.valuehidden === undefined || this.tradeList.valuehidden === '' ||
        this.tagendList.valuehidden === undefined || this.tagendList.valuehidden === '') {
        if (this.tradeList.valuehidden === undefined || this.tradeList.valuehidden === '') {
          this.errormsg1 = '商业客户不能为空'
        } else {
          this.errormsg1 = ''
        }
        if (this.tagendList.valuehidden === undefined || this.tagendList.valuehidden === '') {
          this.errormsg2 = '终端客户不能为空'
        } else {
          this.errormsg2 = ''
        }
      } else {
        let data = {
          scanList: this.scanList,
          jsondata: {
            userid: this.jsonData.userid,
            username: this.jsonData.username,
            billdate: this.jsonData.billdate
          },
          type: this.value,
          tagendList: this.tagendList,
          tradeList: this.tradeList
        }
        this.axios({
          method: 'post',
          url: '/api/lxgzds.scannewsave.do',
          data: qs.stringify(data)
        }).then(res => {
          if (res.data.flag === '1') {
            Toast(res.data.des)
            if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
              this.loginout()
            }
          } else {
            Toast(res.data.des + ' ')
            this.$router.push({ name: 'list', query: { idobject: 'lxgzds' } })
          }
        }).catch(res => {
          this.reserror(res)
        })
        this.errormsg1 = ''
        this.errormsg2 = ''
      }
    },
    openRef (index) {
      if (index === 0) { // 商业客户
        this.clickindex = index
        this.$router.push({
          name: 'ref',
          params: {
            bo: 'account',
            tobo: 'lxgzds',
            field: 'sykh',
            fieldref: 'sname',
            viewid: '16415490103940640827433183585187',
            conditionVal: '',
            conditionValHidden: 'sname:in:;',
            classname: '',
            params: ''
          }
        })
      } else if (index === 1) { // 终端客户
        this.clickindex = index
        this.$router.push({
          name: 'ref',
          params: {
            bo: 'account',
            tobo: 'lxgzds',
            field: 'zdkh',
            fieldref: 'sname',
            viewid: '16415490103940640827433183585187',
            conditionVal: '',
            conditionValHidden: 'sname:in:;',
            classname: '',
            params: ''
          }
        })
      }
    },
    clearRefValue (datamodel) {
      if (datamodel.value === '') {
        datamodel.valuehidden = ''
      }
      this.$forceUpdate()
    },
    onConfirm (value) {
      this.value = value
      this.showPicker = false
    }

  },
  activated () {
    if (this.$store.state.ref_show !== '') {
      this.clickmodel.value = this.$store.state.ref_show
      this.clickmodel.valuehidden = this.$store.state.ref_id
      if (this.clickindex === 0) {
        this.tradeList = this.clickmodel
      } else if (this.clickindex === 1) {
        this.tagendList = this.clickmodel
      }
      this.clickindex = -1
      this.clickmodel = {}
      this.$store.commit('clearRef')
      this.$forceUpdate()
    }
  }
}
</script>

<style>
.fieldgroup_title {
  text-align: left;
  margin: 0px;
  padding: 25px 15px 1px;
  color: rgba(69, 90, 100, 0.6);
  font-weight: normal;
  font-size: 14px;
}

.valueleft {
  min-width: 70%;
  white-space: pre-wrap;
  display: inline-block;
  text-align: left;
  word-break: break-all;
}

.cellvalue .van-cell__value {
  position: relative;
  overflow: hidden;
  color: #323233;
  text-align: left;
  vertical-align: middle;
  word-wrap: break-word;
  flex: 2
}

.cellvalue .van-cell__title {
  color: #999;
}

.swipe-button {
  height: 100%;
}
</style>
